import { initRequest, setMsg, setNotice, setDialog } from '@vben/request'
import type { App } from 'vue'
import {
  useUserStoreWithout,
  // useUserStore
} from '@/store/user'
import {
  useI18n,
  //  useLocale,
  setupI18n,
} from '@vben/locale'
import { getGlobalConfig } from '@vben/utils'
import { projectSetting } from './setting'
// import { localeList } from '@vben/locale/src/config'
import {
  // useAppInject,
  // useHeaderSetting,
  // useMenuSetting,
  // useMultipleTabSetting,
  // useRootSetting,
  // useTabs,
  // useTransitionSetting,
  // useDesign,
  // useAppConfig,
  // usePromise,
  initAppConfig,
} from '@vben/hooks'

// import { useAppStore } from '@/store/modules/app'

// import { siteSetting } from '@/config'
// import { context } from '@vben/request/src'
import { SessionTimeoutProcessingEnum } from '@vben/constants'
import { useAppConfig as appConfigStore } from '@vben/stores'

// To decouple the modules below `packages/*`, they no longer depend on each other
// If the modules are heavily dependent on each other, you need to provide a decoupling method, and the caller will pass the parameters
// Each module needs to provide `bridge` file as a decoupling method

// 为了解耦 `packages/*` 下面各模块，不再相互依赖
// 如果模块相互依赖严重，则需要对外提供解耦方式，由调用方去进行参数传递
// 各个模块需要提供 `bridge` 文件作为解耦方式
async function initPackages() {
  const _initRequest = async () => {
    const { apiUrl } = getGlobalConfig(import.meta.env)
    console.log(apiUrl)

    const { t } = useI18n()

    setMsg((message: string) =>
      uni.showToast({ title: message, icon: 'error' }),
    )
    setNotice((message: string) => uni.showToast({ title: message }))
    setDialog((message: string) =>
      uni.showModal({
        title: t('sys.api.errorTip'),
        content: message,
      }),
    )

    initRequest(
      {
        requestOptions: {
          apiUrl,
          errorMessageMode: 'message',
        },
      },
      {
        getTokenFunction: () => {
          const userStore = useUserStoreWithout()
          return userStore.getAccessToken
        },
        errorFunction: (message: string) => {
          console.log(message)
        },
        noticeFunction: undefined,
        errorModalFunction: undefined,
        timeoutFunction: () => {
          const userStore = useUserStoreWithout()
          userStore.setAccessToken(undefined)
          // userStore.logout(true)
        },
        unauthorizedFunction: (msg?: string) => {
          const userStore = useUserStoreWithout()
          const useAppConfigStore = appConfigStore()
          const stp = useAppConfigStore.sessionTimeoutProcessing
          userStore.setAccessToken(undefined)
          if (stp === SessionTimeoutProcessingEnum.PAGE_COVERAGE) {
            userStore.setSessionTimeout(true)
          } else {
            // userStore.logout(true)
          }
          return msg || t('sys.api.errMsg401')
        },
        handleErrorFunction: (msg, mode) => {
          if (mode === 'modal') {
            // context.modalFunction.error({
            //   title: t('sys.api.errorTip'),
            //   content: msg,
            // })
            uni.showModal({
              title: t('sys.api.errorTip'),
              content: msg,
            })
          } else if (mode === 'message') {
            // context.msgFunction.error(msg)
            uni.showToast({
              title: msg,
            })
          }
        },
      },
    )
  }

  const _initComp = async () => {
    // initComp({
    //   useLocale,
    // localeList,
    //   useAppStore,
    // })
  }
  const _initLayout = async () => {
    // initLayout({
    //   useAppConfig,
    //   useRootSetting,
    //   getMenus,
    //   getCurrentParentPath,
    //   getShallowMenus,
    //   getChildrenMenus,
    //   getAllParentPath,
    //   useHeaderSetting,
    //   useDesign,
    //   useAppInject,
    //   useTabs,
    //   usePromise,
    //   listenerRouteChange,
    //   useUserStore,
    //   useAppStore,
    //   Logo,
    //   useMenuSetting,
    //   useMultipleTabSetting,
    //   useTransitionSetting,
    //   useLockStore,
    //   useLockScreen,
    //   siteSetting,
    // })
  }

  await Promise.all([_initRequest(), _initComp(), _initLayout()])
}

export async function initApplication(app: App) {
  // ! Need to pay attention to the timing of execution
  await setupI18n(app)
  // ! 需要注意调用时机
  await initPackages()

  // Initial project configuration
  initAppConfig(projectSetting)
}
